package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.AuthUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysAuthUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import me.zhyd.oauth.cache.AuthDefaultStateCache;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 第三方认证授权处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/auth")
public class SysAuthController extends BaseController
{
    private AuthStateCache authStateCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserMapper userMapper;

    private final static Map<String, String> auths = new HashMap<String, String>();
    {
        auths.put("gitee", "{\"clientId\":\"e5cf90f79b02128d8f140d6898c480ea9dc5278e15a23617e38b58de8ebdc8be\",\"clientSecret\":\"c02d1df684909ba465cf521d94209e2a50e45f2199244f2af697b514efb38d60\",\"redirectUri\":\"http://127.0.0.1:80/auth/callback/gitee\"}");
        auths.put("github", "{\"clientId\":\"Iv1.1be0cdcd71aca63b\",\"clientSecret\":\"0d59d28b43152bc8906011624db37b0fed88d154\",\"redirectUri\":\"http://127.0.0.1:80/auth/callback/github\"}");
        auths.put("wechat_open", "{\"clientId\":\"wxae32b9dbd949138c\",\"clientSecret\":\"75df4b5c7d69bac9a8a9ea728e4f6977\",\"redirectUri\":\"https://e874-240e-404-7930-6994-80c0-41bd-d6f-ad02.ngrok-free.app/auth/callback/wechat_open\"}");
        auths.put("alipay", "{\"clientId\":\"2021004164699105\",\"clientSecret\":\"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCYd5+vXeVw2qpx6IF+deapuDTIBvgS5GW6aAOPMFvONRl5jOmpjeB/J9Mwbab2v2Ak5Jf90xjHmKafeRu8/G3sBspzk8w8hWiq3e1T96uGiIYqjGAuU4jO7cQa5SKccHy9YGZZljmemrUf+VmhKcRIUx0g9zULNM1PrIbZPgbN3usWw7J3OSak3OeCbXC7ZYQFqNQxYT2I0ZWK1BhKlGkFsZoia+XUGqfvG120NyZ6x5uz+ktHNbrwvVvP9IiN1gIN4u38GsB80+nMeWh4dmMw+wSPoWIHPph0siv+MEQ/1jteZ1QqA/+huKckdo2eWaNBdsHqCZ55l96vZqThxQjPAgMBAAECggEATnOvLRNJjipV7crPZvzPtaDdN9euKjpvxdzjh/hAJPjZpNvHF8GzNHqPhqnFcc3DcPhW5PqME5gOlJxCk5noDbzoy1PPkYyr8M/E4KHeFpmFP7t/ehbtnFxnvdcNWiXfaaqCv7I27893R36MigrtvrFVmbLaDmwbANYrhPkPkzpG2Pfa7A2hhagZMUs8cJrJ0aXV6LickkekFEF+n8B2UbEb2VoHvMnJgHtO5jUdWEG4ZSfVWLhA8V7WxImuRXS6r8Um5ZktAl4rpWKNZlJbkzDFg7mjUPjzfTKbrB63P9thZzOBnOdeAFHjnPrKcpyYsdFbaN1ZNwEzgXH0PPyG4QKBgQDYu1armVA84xpjYHdZ+TfWEBpgU++JPzgiKzRBx2g0frDDF+s/qKN9Rbas7k8L43F6EEuvI4hGxDrXf/oe14LcOX98Udrt+Lle1YzNVIO54S2+OWxbENx/x/af61S+W6C2CkKrn8XG0UgeDQrXOYdri2s7NuoMK7KEUwwpG9QTVwKBgQC0F4HUDNYPIKgAD4ah/M5EPKVOa2qHL/Qqiqf4JfyPfMJV0LeSo2Y8RZrOrAjnCNn1zKyh39Px97SDZ/qicTwVcYSoxgS13oZEED93/DdGI9gzfayR6Y0yg9gZhyAvZ6iNdlvTu4EceFGIS53hn9ByTI2qTVS5+YVgqCK/zQqDSQKBgGdZzpa94Xlnguno0oFhSrMVsr5EyHFWaFpC6ASGJrcBwyEFgvU0YeIXIGmOqrsslqxyoOS/uPimErk5GfkjJBAIizapghEBDsSeaSpxJu+45atUjstOWxfEL2NLQXoVD6o/clONOS76Fb3e0lCX6m/qaBQwt6NeIx7ey2m/D365AoGBAKrzDXg+XwupEhBMrJ4jnaDEeJ5B9LMy3/FqARva4y1JXiebokX9+VQJNnQsdZ7plgxvJwfZshSj76Q1FYMRPdmVEjorDdmdy5HcYoMA1W8tI1NtXlx7eF6VLJK+49xb53GxAmWwPVTLGYnpTYsY6wM0i9023tBSfTtNHv82IV6RAoGBAMZEc8oOHRYVTjJz6wXX1yssDne0ANQiiNI7Za/5j/dj43OHHqQ7KP2pYR+iLa9yGmRWU03xJLJO62fyhqn7MfOTZBzCNvft7dNDlTojkcCzdt/iyC5+NMW9RqU904Qv25zvDRsIdeXnneWNU3qGB6iYdRKL/vGTshQaO+7FkejL\",\"redirectUri\":\"http://192.168.43.146:80/auth/callback/alipay\"}");
        authStateCache = AuthDefaultStateCache.INSTANCE;
    }

    /**
     * 认证授权
     * 
     * @param source
     * @throws IOException
     */
    @GetMapping("/binding/{source}")
    @ResponseBody
    public AjaxResult authBinding(@PathVariable("source") String source, HttpServletRequest request) throws IOException
    {
        LoginUser tokenUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(tokenUser) && userMapper.checkAuthUser(tokenUser.getUserId(), source) > 0)
        {
            return error(source + "平台账号已经绑定");
        }

        String obj = auths.get(source);
        if (StringUtils.isEmpty(obj))
        {
            return error(source + "平台账号暂不支持");
        }
        JSONObject json = JSONObject.parseObject(obj);
        AuthRequest authRequest = AuthUtils.getAuthRequest(source, json.getString("clientId"), json.getString("clientSecret"), json.getString("redirectUri"), authStateCache);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        return success(authorizeUrl);
    }

    @SuppressWarnings("unchecked")
    @GetMapping("/social-login/{source}")
    public AjaxResult socialLogin(@PathVariable("source") String source, AuthCallback callback, HttpServletRequest request)
    {
        String obj = auths.get(source);
        if (StringUtils.isEmpty(obj))
        {
            return AjaxResult.error(10002, "第三方平台系统不支持或未提供来源");
        }
        JSONObject json = JSONObject.parseObject(obj);
        AuthRequest authRequest = AuthUtils.getAuthRequest(source, json.getString("clientId"), json.getString("clientSecret"), json.getString("redirectUri"), authStateCache);
        AuthResponse<AuthUser> response = authRequest.login(callback);
        if (response.ok())
        {
            LoginUser tokenUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(tokenUser))
            {
                SysUser user = userMapper.selectAuthUserByUuid(source + response.getData().getUuid());
                if (StringUtils.isNotNull(user))
                {
                    String token = tokenService.createToken(SecurityUtils.getLoginUser());
                    return success().put(Constants.TOKEN, token);
                }
                // 若已经登录则直接绑定系统账号
                SysAuthUser authUser = new SysAuthUser();
                authUser.setAvatar(response.getData().getAvatar());
                authUser.setUuid(source + response.getData().getUuid());
                authUser.setUserId(SecurityUtils.getUserId());
                authUser.setUserName(response.getData().getUsername());
                authUser.setNickName(response.getData().getNickname());
                authUser.setEmail(response.getData().getEmail());
                authUser.setSource(source);
                userMapper.insertAuthUser(authUser);
                String token = tokenService.createToken(SecurityUtils.getLoginUser());
                return success().put(Constants.TOKEN, token);
            }
            SysUser authUser = userMapper.selectAuthUserByUuid(source + response.getData().getUuid());
            if (StringUtils.isNotNull(authUser))
            {
                SysUser user = userService.selectUserByUserName(authUser.getUserName());
                if (StringUtils.isNull(user))
                {
                    throw new ServiceException("登录用户：" + user.getUserName() + " 不存在");
                }
                else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
                {
                    throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已被删除");
                }
                else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
                {
                    throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已停用");
                }
                LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
                String token = tokenService.createToken(loginUser);
                return success().put(Constants.TOKEN, token);
            }
            else
            {
                return AjaxResult.error(10002, "对不起，您没有绑定注册用户，请先注册后在个人中心绑定第三方授权信息！");
            }
        }
        return AjaxResult.error(10002, "对不起，授权信息验证不通过，请联系管理员");
    }

    /**
     * 取消授权
     */
    @DeleteMapping(value = "/unlock/{authId}")
    public AjaxResult unlockAuth(@PathVariable Long authId)
    {
        return toAjax(userMapper.deleteAuthUser(authId));
    }
}
